<template>
    <!-- 考试主容器 -->
    <div class="exam-container">
        <!-- 左侧导航区 -->
        <div class="nav-panel">
            <!-- 用户信息栏 -->
            <div class="student-info">
                <h2>考生信息</h2>
                <el-descriptions v-if="userInfo" :column="1" class="info-detail">
                    <el-descriptions-item label="考生账号">
                        <el-tag type="info">{{ userInfo.userName }}</el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="考生姓名">
                        <span class="highlight-text">{{ userInfo.nickName }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="考生性别">
                        <span class="gender-tag">{{ userInfo.sex === '1' ? '女' : '男' }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="身份证号">
                        <span class="highlight-text">{{ userInfo.idCardNo }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="所属机构">
                        <span class="highlight-text">{{ depart }}</span>
                    </el-descriptions-item>
                </el-descriptions>
            </div>

            <!-- 题号导航 -->
            <h2 style="margin-top: 20%;">试题标号</h2>
            <div class="question-nav">
                <div v-for="(group, type) in questionGroups" :key="type" class="question-group">
                    <h3 class="group-title">{{ questionTypeNames[type] }}</h3>
                    <div class="nav-items">
                        <div v-for="(q, idx) in group" :key="q.originIndex" :class="['nav-item', {
                            current: currentIndex === q.originIndex,
                            answered: answers[q.originIndex]
                        }]" @click="currentIndex = q.originIndex">
                            {{ q.originIndex + 1 }} <!-- 全局序号 -->
                        </div>
                    </div>
                </div>
            </div>

            <!-- 状态筛选 -->
            <div class="status-filter">
                <div class="filter-item" v-for="(item, index) in filters" :key="index">
                    <div :class="['color-block', item.type]"></div>
                    {{ item.label }}
                </div>
            </div>
        </div>

        <!-- 右侧答题区 -->
        <div class="content-panel">
            <div class="header-status">
                <div></div>
                <div class="paper-title">{{ paperinfo.name }}</div>
                <div class="timer" v-if="remainingTime > 0" :class="{ 'time-alert': remainingTime < 300 }">剩余时长：{{
                    formattedTime }}</div>
                <div v-if="remainingTime <= 0" class="time-alert">考试已结束</div>
            </div>
            <div class="answered-count">
                <span>已答 {{ answeredCount }}/{{ questions.length }}</span>
            </div>
            <!-- 题目区域 -->
            <div class="question-area" v-if="currentQuestion">
                <div class="q-wrap">
                    <div class="q-title">
                        <!-- <div class="question-title">第{{ currentIndex + 1 }}题：</div> -->
                        <div class="question-stem"><span style="font-weight: 600;">第{{ currentIndex + 1
                                }}题：</span><span style="color: blue;">{{
                                    '（' + questionTypeNames[currentQuestion.type] + '）' }}</span>{{
                                    currentQuestion.content }}
                        </div>
                    </div>

                    <!-- 多选题使用checkbox -->
                    <el-checkbox-group v-if="currentQuestion.type == 3" v-model="multiAnswers[currentIndex]"
                        @change="handleMultiAnswer" class="exam-checkbox-group">
                        <el-checkbox v-for="option in currentQuestion.answerList" :key="option.id"
                            :value="option.answerOption" class="exam-checkbox-item">
                            <!-- 选项内容 -->
                            <div class="option-content">
                                <span class="option-marker">{{ option.answerOption }}</span>
                                <span class="option-text">{{ option.content }}</span>
                            </div>
                        </el-checkbox>
                    </el-checkbox-group>

                    <!-- 选项列表 -->
                    <el-radio-group v-else @change="handleRadio" v-model="answers[currentIndex]"
                        class="exam-radio-group">
                        <el-radio v-for="(option, index) in currentQuestion.answerList" :key="option.id"
                            :value="option.answerOption" class="exam-radio-item">
                            <div class="option-content">
                                <span class="option-marker">{{ option.answerOption }}</span>
                                <span class="option-text">{{ option.content }}</span>
                            </div>
                        </el-radio>
                    </el-radio-group>
                </div>
            </div>
            <el-dialog :show-close="false" :close-on-click-modal="false" v-model="showConfirmDialog" title="确认提交"
                width="30%">
                <div class="confirm-content">
                    <el-icon :size="40" color="#67C23A" class="dialog-icon">
                        <Warning />
                    </el-icon>
                    <span>确定要提交试卷吗？提交后不可修改！</span>
                </div>

                <template #footer>
                    <el-button @click="showConfirmDialog = false">返回继续答题</el-button>
                    <el-button type="primary" @click="handleRealSubmit" :loading="submitting">
                        确认提交
                    </el-button>
                </template>
            </el-dialog>

            <!-- 得分展示弹窗 -->
            <el-dialog :show-close="false" :close-on-click-modal="false" v-model="showResultDialog" title="考试结果"
                width="35%">
                <div class="result-content">
                    <el-result :icon="paperInfo.result == '1' ? 'success' : 'error'" :title="resultTitle"
                        :sub-title="resultSubTitle">
                        <template #extra>
                            <div class="score-panel">
                                <!-- 考试用时 -->
                                <div class="score-item">
                                    <span class="label">考试用时：</span>
                                    <el-tag type="info">{{ formatDuration(paperInfo.createTime,
                                        paperInfo.endTime) }}</el-tag>
                                </div>

                                <!-- 考试得分 -->
                                <div class="score-item">
                                    <span class="label">考试得分：</span>
                                    <el-tag :type="paperInfo.result == 1 ? 'success' : 'danger'">
                                        {{ paperInfo.examMark }} 分
                                    </el-tag>
                                </div>

                                <!-- 及格分数线 -->
                                <div class="score-item">
                                    <span class="label">及格分数：</span>
                                    <el-tag type="warning">
                                        {{ paperInfo.passMark }} 分
                                    </el-tag>
                                </div>
                            </div>
                        </template>
                    </el-result>
                </div>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button type="primary" size="default" class="confirm-btn" @click="handResultDialog">
                            确定
                        </el-button>
                    </div>
                </template>
            </el-dialog>
            <!-- 操作按钮 -->
            <div class="action-bar">
                <el-button type="primary" plain :disabled="currentIndex === 0" @click="currentIndex--">
                    上一题
                </el-button>

                <el-button type="primary" plain :disabled="currentIndex === questions.length - 1"
                    @click="currentIndex++">
                    下一题
                </el-button>

                <el-button :disabled="remainingTime <= 0" type="danger" plain @click="handleSubmit">
                    提交试卷
                </el-button>
            </div>
        </div>

        <!-- 离开确认弹窗 -->
        <el-dialog v-model="showLeaveDialog" title="操作确认" width="500px" :close-on-click-modal="false"
            custom-class="warning-dialog">
            <div class="confirm-content">
                <el-icon :size="40" color="#F56C6C" class="dialog-icon">
                    <Warning />
                </el-icon>
                <span class="warning-text">离开页面试卷将自动提交，确认离开吗？</span>
            </div>

            <template #footer>
                <el-button @click="cancelLeave" size="default">取消</el-button>
                <el-button type="primary" size="default" @click="confirmLeave"
                    style="background: #F56C6C; border-color: #F56C6C">
                    确认离开
                </el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, onBeforeUnmount } from 'vue'
import { Warning } from '@element-plus/icons-vue'
import { examApi } from '@/api/exam'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
const route = useRoute()
const router = useRouter()
console.log(route.params.paperId);
const showLeaveDialog = ref(false)
const pendingNavigation = ref(null)
// 考试数据
const currentIndex = ref(0) // 当前第6题
const answers = ref([])

const showConfirmDialog = ref(false)
const showResultDialog = ref(false)
const submitting = ref(false)
const remainingTime = ref(4000) // 09:28 剩余秒数
const handleRadio = (e) => {
    console.log(e);
}
const handResultDialog = () => {
    showResultDialog.value = false
    window.removeEventListener('beforeunload', handleBeforeUnload)
    router.beforeEach(() => { }) // 清除全局路由守卫
    window.location.replace('/confirm')
}
// 状态筛选标签
const filters = [
    { type: 'answered', label: '已答' },
    { type: 'unanswered', label: '未答' },
    { type: 'current', label: '当前' }
    // { type: 'marked', label: '标记' }
]
const timer = ref()
const userInfo = ref()
const depart = ref()
//获取登录信息
const getUserinfo = async () => {
    examApi.getProfile().then(res => {
        console.log(res);
        if (res.code == 200) {
            userInfo.value = res.data.user
            depart.value = res.data.departName
        }
    })
}
getUserinfo()
// 确保remainingTime在组件挂载时初始化
onMounted(async () => {
    // 检查考试状态
    if (remainingTime.value <= 0) {
        ElMessage.warning('考试已结束，即将跳转')
        // return router.push('/result')
    }

    // 启动定时器
    timer.value = setInterval(() => {
        remainingTime.value > 0
            ? remainingTime.value--
            : handleRealSubmit()
    }, 1000)
})

onUnmounted(() => {
    clearInterval(timer.value)
})
const questions = ref([])

// 当前题目
const currentQuestion = computed(() =>
    questions.value[currentIndex.value]
)



const id = ref()
const paperinfo = ref({ name: '试题' })
//获取详情
const detail = () => {
    examApi.startExam({ paperId: route.params.paperId }).then(res => {
        console.log(res);
        if (res.code == 200) {
            paperinfo.value = res.data
            remainingTime.value = res.data.examDurationMinutes * 60
            id.value = res.data.id
            questions.value = res.data.paperContentList
            answers.value = Array(res.data.paperContentList.length).fill(null)
        } else {
            router.go(-1)
        }
    })
}
detail()

// 计算属性
const formattedTime = computed(() => {
    const mins = Math.floor(remainingTime.value / 60)
    const secs = remainingTime.value % 60
    return `${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`
})

const answeredCount = computed(() =>
    answers.value.filter(a => a !== null).length
)
// 事件处理
const handleSubmit = () => {
    console.log(answers.value);
    // 提交考试逻辑
    showConfirmDialog.value = true
}


// 新增状态管理
const questionTypeNames = {
    1: '判断题',
    2: '单选题',
    3: '多选题'
}

// 分组后的题目数据
const questionGroups = computed(() => {
    const groups = { 1: [], 2: [], 3: [] }
    questions.value.forEach((q, index) => {
        const group = groups[q.type]
        group.push({
            ...q,
            originIndex: index,  // 保留原始索引
            displayNumber: group.length + 1 // 分组内序号
        })
    })
    return groups
})

// 多选题答案单独处理（数组格式）
const multiAnswers = ref([])

// 多选答案处理
// 修改多选答案处理方法
const handleMultiAnswer = (index) => {
    const selectedOptions = multiAnswers.value[index]
    console.log(multiAnswers.value[index], 11);

    answers.value[currentIndex.value] = index?.length > 0
        ? index.join(',')
        : null
}


// 生成提交数据
const generateSubmitData = () => {
    return {
        id: id.value,       // 考试记录ID（需从接口获取）
        paperId: route.params.paperId, // 当前试卷ID（路由参数获取）
        paperContentList: questions.value.map((q, index) => ({
            id: q.id,                   // 题目ID（来自接口数据）
            paperAnswer: answers.value[index]                   // 未答题目处理
        }))
    }
}
const paperInfo = ref()
const resultTitle = computed(() =>
    paperInfo.value.result == 1 ? '恭喜你，通过了本次考试！' : '很遗憾，您未通过本次考试'
)
const resultSubTitle = computed(() =>
    paperInfo.value.result == 1 ? '您的成绩已达到合格标准' : '请继续努力，下次一定成功！'
)

const formatDuration = (startTime, endTime) => {
    const start = new Date(startTime).getTime()
    const end = new Date(endTime).getTime()

    const diff = end - start
    const totalSeconds = Math.floor(diff / 1000)

    const minutes = Math.floor(totalSeconds / 60)
    const seconds = totalSeconds % 60

    return `${String(minutes).padStart(2, '0')}分${String(seconds).padStart(2, '0')}秒`
}
// 实际提交逻辑
const handleRealSubmit = async () => {
    submitting.value = true
    const params = generateSubmitData()
    console.log(params);
    await examApi.submitExam(params).then((res) => {
        if (res.code == 200) {
            paperInfo.value = res.data
            showConfirmDialog.value = false
            showResultDialog.value = true
        }
    })
    clearInterval(timer.value)
    submitting.value = false

}

//离开页面提交逻辑
const handleRealSubmit1 = async () => {
    const params = generateSubmitData()
    console.log(params);
    await examApi.submitExam(params).then((res) => {
        if (res.code == 200) {
            paperInfo.value = res.data
        }
    })
    clearInterval(timer.value)
}
// / 浏览器返回/刷新拦截
const handleBeforeUnload = (e) => {
    if (remainingTime.value > 0) {
        e.preventDefault()
        e.returnValue = ''
        // handleAutoSubmit()
    }
}

// 路由离开拦截
const beforeRouteHandler = (to, from, next) => {
    pendingNavigation.value = next
    showLeaveDialog.value = true
}

// 确认提交并离开
const confirmLeave = async () => {
    await handleRealSubmit1()
    window.removeEventListener('beforeunload', handleBeforeUnload)
    router.beforeEach(() => { }) // 清除全局路由守卫
    if (pendingNavigation.value) {
        pendingNavigation.value()
    }
    window.location.replace('/confirm')
}

// 取消离开
const cancelLeave = () => {
    pendingNavigation.value(false)
    showLeaveDialog.value = false
}

onMounted(() => {
    window.addEventListener('beforeunload', handleBeforeUnload)
    router.beforeEach(beforeRouteHandler)
})

onBeforeUnmount(() => {
    window.removeEventListener('beforeunload', handleBeforeUnload)
    router.beforeEach(() => { })
})
</script>

<style lang="scss" scoped>
.warning-dialog {
    .el-dialog__header {
        border-bottom: 1px solid #F56C6C;

        .el-dialog__title {
            color: #F56C6C;
            font-size: 18px;
        }
    }

    .dialog-content {
        display: flex;
        align-items: center;
        padding: 20px 0;

        .dialog-icon {
            margin-right: 15px;
        }

        .warning-text {
            color: #606266;
            font-size: 16px;
        }
    }

    .el-dialog__footer {
        padding: 20px;
        text-align: center;
    }
}

/* 弹窗样式匹配系统主题 */
confirm {
    border: 2px solid #f56c6c;
    border-radius: 8px;
    padding: 20px;
    background: #000;
    color: #fff;
}

.panel-title {
    font-size: 18px;
    font-weight: 600;
}

.info-detail {
    :deep(.el-descriptions__label) {
        width: 80px;
        color: #606266;
        font-weight: 500;
    }

    .highlight-text {
        color: #303133;
        font-weight: 500;
    }

    .gender-tag {
        padding: 4px 12px;
        border-radius: 4px;
        background: #e8f4e9;
        color: #13ce66;
    }

    .id-number {
        letter-spacing: 1px;
        font-family: monospace;
    }
}

/* 选项组容器 */
.exam-radio-group {
    // width: 100%;
    display: flex;
    flex-direction: column;
}

:deep(.option-text) {
    font-size: 22px !important;
}

.option-content {
    display: flex;
}

/* 每个选项独占一行 */
.el-radio {
    width: 100%;
    margin: 0 0 8px 0 !important;
    padding: 8px 12px 8px 0;
    border-radius: 4px;
    transition: background-color 0.2s;
}

/* 鼠标悬停整行高亮 */
.el-radio:hover {
    background-color: #f5f5f5;
}

/* 选项标签容器 */
.el-radio__label {
    display: flex;
    align-items: center;
    width: 100%;
    padding: 0 !important;
}

/* 标号样式 */
.option-marker {
    display: inline-block;
    width: 30px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    border: 1px solid #ddd;
    border-radius: 4px;
    margin-right: 12px;
    font-weight: 500;
    background: #f8f9fa;
}

/* 选中时标号样式 */
.el-radio.is-checked .option-marker {
    background-color: #13ce66;
    color: white;
    border-color: #1da55a;
}

/* 隐藏原生radio图标 */
:deep(.el-radio__input) {
    display: none !important;
}

/* 隐藏原生radio图标 */
:deep(.el-checkbox__input) {
    display: none;
}

/* 选项文字样式 */
.option-text {
    flex: 1;
    color: #333;
    font-size: 15px;
}

.paper-title {
    font-weight: 600;
}

.exam-container {
    display: flex;
    background: #f8fafb;
    height: 100%;
    border-radius: 8px;

    .nav-panel {
        width: 280px;
        border-right: 1px solid #e8e8e8;
        padding: 20px;
        background-color: #fff;

        .student-info {
            padding-bottom: 50px;
            border-bottom: 1px solid #e8e8e8;
            // padding: 20px;
        }

        .question-nav {
            display: flex;
            flex-direction: column;
            grid-template-columns: repeat(5, 1fr);
            gap: 10px;

            /* 题号分组样式 */
            .question-group {
                margin-bottom: 20px;

                .group-title {
                    color: #2b77f2;
                    font-size: 14px;
                    margin: 10px 0;
                    padding-left: 8px;
                    border-left: 3px solid #2b77f2;
                }

                .nav-items {
                    display: grid;
                    grid-template-columns: repeat(5, 1fr);
                    gap: 8px;
                }
            }

            .nav-item {
                // @include flex-center;
                width: 40px;
                height: 40px;
                line-height: 40px;
                border: 1px solid #e8e8e8;
                border-radius: 4px;
                text-align: center;
                cursor: pointer;

                &.answered {
                    background: #409eff;
                    color: white;
                    border-color: #409eff;
                }

                &.current {
                    background: #13ce66;
                    color: white;
                    border-color: #13ce66;
                }
            }
        }

        .status-filter {
            margin-top: 30px;

            .filter-item {
                display: flex;
                align-items: center;
                margin: 8px 0;

                .color-block {
                    width: 16px;
                    height: 16px;
                    margin-right: 8px;

                    &.answered {
                        background: #409eff;
                    }

                    &.unanswered {
                        background: #e8e8e8;
                    }

                    &.current {
                        background: #13ce66;
                    }

                    &.marked {
                        background: #ffba00;
                    }
                }
            }
        }
    }

    .content-panel {
        flex: 1;

        .answered-count {
            padding: 20px;
            display: flex;
            align-items: center;
            gap: 6px;
            font-weight: 600;
            color: #13ce66;
            font-size: 28px;
        }

        .header-status {
            padding: 20px;
            // padding: 0 10px;
            border-bottom: 1px solid #e8e8e8;
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 24px;
            font-size: 28px;


            .timer {
                margin-left: 50px;
                display: flex;
                align-items: center;
                gap: 6px;
                font-weight: 600;

                &.time-alert {
                    color: #ffeb3b;
                }
            }
        }

        .exam-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 30px;

            .timer {
                color: #13ce66;
                font-weight: bold;
            }

            .time-alert {
                color: #f56c6c;
            }
        }

        .question-area {
            // height: 100%;
            padding: 20px;
            font-size: 25px;
            display: flex;
            flex-direction: column;

            /* 多选选项样式 */
            .exam-checkbox-group {
                display: flex;
                flex-direction: column;

                .el-checkbox :hover {
                    background-color: #f5f5f5;
                }

                .el-checkbox {
                    width: 100%;
                    margin: 0 0 8px 0 !important;
                    border-radius: 4px;
                    padding: 10px 12px 10px 0;

                    &:deep(.el-checkbox__label) {
                        transition: background-color 0.2s;
                        margin: 0 0 8px 0 !important;
                        padding: 10px 12px 10px 8px;
                        display: flex;
                        align-items: center;
                        width: 100%;
                    }

                    .option-text {
                        flex: 1;
                        color: #333;
                        font-size: 15px;
                    }
                }

                .option-content {
                    display: flex;
                }

                .is-checked .option-marker {
                    color: white;
                    background: #13ce66;
                    border-color: #1da55a;
                }
            }

            .q-wrap {
                padding-top: 20px;
            }

            .q-title {
                display: flex;
            }
        }

        .question-title {
            color: #333;
            font-weight: 600;
        }

        .question-stem {
            color: #333;
            margin-bottom: 20px;
            color: #3b3d41;
        }

        .option-item {
            display: block;
            margin: 12px 0;
            padding: 12px;
            border-radius: 4px;
            border: 1px solid #e8e8e8;

            &:hover {
                background: #f5f7fa;
            }
        }

        .action-bar {
            padding-right: 20%;
            // margin-top: 50px;
            display: flex;
            justify-content: flex-end;
            gap: 12px;

            :deep(.el-button) {
                padding: 12px 24px;
            }
        }
    }
}

.confirm-content {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 15px;
    padding: 20px 0;

    .dialog-icon {
        margin-right: 10px;
    }
}

.score-panel {
    padding: 15px;
    background: #f8fafc;
    border-radius: 8px;
}

.score-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 12px 0;
    padding: 8px 12px;
    background: white;
    border-radius: 6px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.label {
    font-weight: 500;
    color: #606266;
}

/* 调整标签大小 */
.el-tag {
    font-size: 14px;
    padding: 8px 12px;
    min-width: 80px;
    text-align: center;
}

/* 保持与主界面一致的绿色主题 */
:deep(.el-dialog) {
    border-radius: 12px;

    .el-dialog__header {
        background: #f8fff8;
        border-bottom: 1px solid #e8f4e9;
    }

    .el-button {
        padding: 12px 24px;
        border-radius: 6px;

        &:last-child {
            background: #67C23A;
            border-color: #67C23A;
        }
    }
}

:deep(.el-dialog) {
    border-radius: 12px;

    .el-dialog__header {
        border-bottom: 1px solid #e8e8e8;

        .el-dialog__title {
            color: #1a3d5d;
            font-size: 18px;
        }
    }

    .confirm-btn {
        width: 120px;
        background: #13ce66;
        border-color: #13ce66;

        &:hover {
            opacity: 0.9;
        }
    }
}
</style>